package com.zk.babala.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlightHelper;
import androidx.leanback.widget.GridLayoutManager;
import androidx.leanback.widget.ItemBridgeAdapter;
import androidx.leanback.widget.VerticalGridView;
import androidx.recyclerview.widget.RecyclerView;

import com.zk.babala.BabalaApp;
import com.zk.babala.R;
import com.zk.babala.entity.CategoryInfo;
import com.zk.babala.entity.Movie;
import com.zk.babala.presenter.MovieItemPresenter;
import com.zk.babala.util.GiteeUtil;
import com.zk.babala.util.HistoryUtil;
import com.zk.babala.util.LineUtil;
import com.zk.babala.util.RequestUtil;
import com.zk.babala.util.UpdateApp;

import java.util.List;

import cn.hutool.core.util.StrUtil;

/**
 * 主页面
 */
public class IndexActivity extends Activity {
    VerticalGridView verticalGridView;
    int currPage = 0;
    ArrayObjectAdapter objectAdapter;
    Button currentItem;
    Button currentChildItem;
    LinearLayout categoryLinearLayout;
    LinearLayout categoryChildLinearLayout;
    Button searchBtn;
    Boolean clickHistory = false;
    ProgressBar loadingProgress;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index_activity);
        searchBtn = findViewById(R.id.search);
        searchBtn.setOnClickListener(view -> toSearch());
        categoryLinearLayout = findViewById(R.id.select_list);
        categoryChildLinearLayout = findViewById(R.id.select_child_list);
        verticalGridView = findViewById(R.id.select_item_list);
        // 显示加载进度条
        loadingProgress = findViewById(R.id.loading_progress);
        findViewById(R.id.setting).setOnClickListener(view -> toSetting());
        findViewById(R.id.update).setOnClickListener(view -> toUpdate());
        findViewById(R.id.delete_history).setOnClickListener(view -> toDeleteHis());
        findViewById(R.id.down_history).setOnClickListener(view -> toDownHis());
        findViewById(R.id.upload_history).setOnClickListener(view -> toUpHis());
        findViewById(R.id.history).setOnClickListener(view -> toHistory());
        findViewById(R.id.live).setOnClickListener(view -> toLive());
        try {
            if (HistoryUtil.getHistoryInstance().getStartToLive()) {
                Intent intent = new Intent(this, LiveActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
            initGridView();
            initCategory();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), "初始化失败 " + e.getMessage(), Toast.LENGTH_SHORT);
        }
        if (StrUtil.isNotEmpty(LineUtil.getLineUtil().getIp())) {
            RequestUtil.setHeader("X-Forwarded-For", LineUtil.getLineUtil().getIp());
        }

    }

    private void initCategory() {
        List<CategoryInfo> categoryList = BabalaApp.getSourceParse().getCategory();
        categoryList.forEach(category -> {
            View seletctView = LayoutInflater.from(this).inflate(R.layout.select_item, categoryLinearLayout, false);
            Button item = seletctView.findViewById(R.id.category_item_button);
            item.setText(category.getTitle());
            item.setTextSize(14);
            item.setOnClickListener(view -> {
                categoryChildLinearLayout.removeAllViews();
                category.getChildList().forEach(child -> {
                    View childSelectView = LayoutInflater.from(this).inflate(R.layout.select_item, categoryChildLinearLayout, false);
                    Button childItem = childSelectView.findViewById(R.id.category_item_button);
                    childItem.setText(child.getTitle());
                    childItem.setOnClickListener(childView -> {
                        loadData(child.getUrl());
                        if (currentChildItem != null) {
                            currentChildItem.setTextColor(ContextCompat.getColor(this, R.color.choice_normal));
                        }
                        childItem.setTextColor(ContextCompat.getColor(this, R.color.fastlane_background));
                        currentChildItem = childItem;

                    });
                    categoryChildLinearLayout.addView(childSelectView);
                });
                if (currentItem != null) {
                    currentItem.setTextColor(ContextCompat.getColor(this, R.color.choice_normal));
                }
                item.setTextColor(ContextCompat.getColor(this, R.color.fastlane_background));
                currentItem = item;
                clickHistory = false;
                loadData(category.getUrl());
            });
            categoryLinearLayout.addView(seletctView);

        });
        categoryLinearLayout.post(() ->
                categoryLinearLayout.requestFocus()
        );
        verticalGridView.post(() -> loadData(categoryList.get(0).getUrl()));
    }

    private void initGridView() {
        verticalGridView.setNumColumns(6);
        MovieItemPresenter presenter = new MovieItemPresenter();
        //创建ObjectAdapter，用于提供数据，当有多种类型时，传入PresenterSelector
        objectAdapter = new ArrayObjectAdapter(presenter);
        ItemBridgeAdapter bridgeAdapter = new ItemBridgeAdapter(objectAdapter);
        //将ItemBridgeAdapter传入HorizontalGridView
        verticalGridView.setAdapter(bridgeAdapter);
        //设置上焦动画
        FocusHighlightHelper.setupHeaderItemFocusHighlight(bridgeAdapter);
        //监听滑动加载更多数据
        verticalGridView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 记录当前滑动状态
                if (newState == RecyclerView.SCROLL_STATE_IDLE) { //当前状态为停止滑动
                    if (verticalGridView.getSelectedPosition() < 12) { // 到达顶部
                        categoryLinearLayout.setVisibility(View.VISIBLE);
                        categoryChildLinearLayout.setVisibility(View.VISIBLE);
                    } else {
                        categoryLinearLayout.setVisibility(View.GONE);
                        categoryChildLinearLayout.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                recyclerView.post(() -> {
                    GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                    int SelectedPosition = verticalGridView.getSelectedPosition();
                    assert layoutManager != null;
                    int totalItemCount = layoutManager.getItemCount();
                    if (currPage != -1 && (totalItemCount - SelectedPosition) <= 6) {
                        List<Movie> loadNextList = BabalaApp.getSourceParse().loadNext();
                        if (loadNextList.isEmpty()) {
                            currPage = -1;
                            if (totalItemCount > 12) {
                                Toast.makeText(recyclerView.getContext(), "已经到底啦~~", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            currPage++;
                            addData(loadNextList);
                        }
                    }
                });

            }
        });

    }

    private void loadData(String url) {
        currPage = 0;
        objectAdapter.clear();
        try {
            verticalGridView.setVisibility(View.GONE);
            loadingProgress.setVisibility(View.VISIBLE);
            List<Movie> list = BabalaApp.getSourceParse().getMovies(url);
            addData(list);
        } catch (Exception e) {
            Toast.makeText(this, "初始化失败，请查看网页提示或切换线路~" + e.getMessage(), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(BabalaApp.getContext(), CookiesWebViewActivity.class);
            intent.putExtra("url", LineUtil.getLineUtil().swapUrl(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BabalaApp.getContext().startActivity(intent);
        } finally {
            verticalGridView.setVisibility(View.VISIBLE);
            loadingProgress.setVisibility(View.GONE);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (searchBtn.hasFocus()) {
                android.app.AlertDialog dlg = new AlertDialog.Builder(this)
                        .setTitle("确认退出APP?")
                        .setPositiveButton("确认", (dialog, whichButton) -> this.finishAffinity()).create();
                dlg.show();
            } else {
                categoryLinearLayout.setVisibility(View.VISIBLE);
                categoryChildLinearLayout.setVisibility(View.VISIBLE);
                searchBtn.requestFocus();
                return false;
            }


        }
        return super.onKeyDown(keyCode, event);
    }

    private void addData(List<Movie> list) {
        objectAdapter.addAll(currPage * list.size(), list);
    }

    public void toSetting() {
        Intent intent = new Intent(this, SettingActivity.class);
        this.startActivity(intent);
    }


    public void toLive() {
        Intent intent = new Intent(this, LiveActivity.class);
        this.startActivity(intent);
    }

    public void toDeleteHis() {
        android.app.AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("确认清除所有历史记录?")
                .setPositiveButton("确认", (dialog, whichButton) -> {
                    HistoryUtil.getHistoryInstance().clearAll();
                    onResume();
                    Toast.makeText(this, "历史记录已清除！", Toast.LENGTH_SHORT).show();
                    toHistory();
                }).create();
        dlg.show();
    }

    public void toUpHis() {
        android.app.AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("确认上传历史记录?")
                .setPositiveButton("确认", (dialog, whichButton) -> {
                    GiteeUtil.uploadFile(HistoryUtil.getHistoryInstance().getHistoryJson());
                    Toast.makeText(this, "上传成功！", Toast.LENGTH_SHORT).show();
                }).create();
        dlg.show();
    }


    public void toDownHis() {
        android.app.AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("确认下载历史记录?")
                .setPositiveButton("确认", (dialog, whichButton) -> {
                    HistoryUtil.getHistoryInstance().saveDataJson(GiteeUtil.getRemoteHistoryJson());
                    Toast.makeText(this, "下载历史记录成功！", Toast.LENGTH_SHORT).show();
                    toHistory();
                }).create();
        dlg.show();
    }

    public void toSearch() {
        Intent intent = new Intent(this, SearchActivity.class);
        this.startActivity(intent);
    }

    public void toHistory() {
        categoryChildLinearLayout.setVisibility(View.GONE);
        clickHistory = true;
        currPage = -1;
        objectAdapter.clear();
        objectAdapter.addAll(0, HistoryUtil.getHistoryInstance().getHistoryList());
    }

    public void toUpdate() {
        android.app.AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("确认更新APP?")
                .setPositiveButton("确认", (dialog, whichButton) ->
                        new UpdateApp(this).ShowDownloadDialog()
                ).create();
        dlg.show();
    }

    @Override
    protected void onResume() {
        if (clickHistory) {
            toHistory();
        }
        super.onResume();
    }

}